package vip.geeker.iotms.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import vip.geeker.iotms.dto.UserDto;
import vip.geeker.iotms.help.Constants;
import vip.geeker.iotms.persistance.model.User;
import vip.geeker.iotms.service.impl.UserService;
import vip.geeker.iotms.utils.ObjectUtils;
import vip.geeker.iotms.utils.vcode.Captcha;
import vip.geeker.iotms.utils.vcode.GifCaptcha;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@Slf4j
public class BaseController {

    @RequestMapping("/")
    public String welcome() throws IOException {
        return Constants.INDEX;
    }


    @Resource
    private UserService userService;

    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";


    /**
     * 初始化时间格式和参数空字符转化为null
     */
    @InitBinder
    protected void initBinder(ServletRequestDataBinder binder) {
        //格式化时间
        SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
        CustomDateEditor editor = new CustomDateEditor(df, true);
        binder.registerCustomEditor(Date.class, editor);
        //空字符转换
        binder.registerCustomEditor(Object.class, new PropertiesEditor() {
            @Override
            public void setAsText(String text) {
                text = text.trim();
                if (StringUtils.isEmpty(text)) {
                    text = null;
                }
                setValue(text);
            }
        });
    }

    @PostMapping("/login")
    public Object loginPost(String loginName, String password, String security_code, Model model, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String _code = (String) session.getAttribute("_code");
        if (!security_code.equalsIgnoreCase(_code)) {
            model.addAttribute("errorInfo", "验证码错误！");
            model.addAttribute("errorCode", "fail");
            log.error("登陆失败：验证码错误！应输入验证码：{},实际输入验证码：{}", _code, security_code);
            return Constants.INDEX;
        }

        User user = User.builder().loginName(loginName).loginPwd(password).build();
        UserDto userDto = userService.auth(user);
        if (ObjectUtils.isNullOrEmpty(userDto)) {
            model.addAttribute("errorInfo", "用户名或密码错误！");
            model.addAttribute("errorCode", "fail");
            return Constants.INDEX;
        }
        session.setAttribute(Constants.USER_SESSION_KEY, userDto);
        session.setAttribute("realName", userDto.getRealName());
        return Constants.MAIN;
    }


    @RequestMapping("/loginOut")
    public Object loginOut(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute(Constants.USER_SESSION_KEY);
        return "redirect:/";
    }


    @GetMapping(value = "/getGifCode")
    public void getGifCode(HttpServletResponse response, HttpServletRequest request) {
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/gif");
            /*
             * gif格式动画验证码
             * 宽，高，位数。
             */
            Captcha captcha = new GifCaptcha(106, 34, 4);
            //输出
            captcha.out(response.getOutputStream());
            HttpSession session = request.getSession(true);
            //存入Session
            session.setAttribute("_code", captcha.text());
        } catch (Exception e) {
            log.error("获取验证码异常:{}", e);
        }
    }


    @RequestMapping("/data")
    public String data() {
        return Constants.DATA;
    }


}
//
